/**
 * @file path模块
 * @author fanxueliang@qq.com
 */

/**
 * 根据源路径和转移路径，计算最终路径
 * a.b.c  ../../   ---->   a
 * a.b.c  /e/f/g   ---->   e.f.g
 * a.b.c  $.e.f.g   ---->   e.f.g
 * a.[0].b.c   ../../  --> a.[0]
 * a.b  ../../  ----> undefined
 * @param sourcePath 源路径
 * @param transferPath 需要转移的路径
 * @return 最终返回的路径
 */
export function getFieldPath(sourcePath: string, transferPath: string): string | undefined {
    const sourcePathArr = sourcePath.split('.').filter((v) => !!v);
    transferPath = transferPath.replace(/^\$\./, '/');
    const transPathArr = transferPath.split('/').filter((v) => !!v);
    // absolute path
    if (transferPath.startsWith('/')) {
        const result: string[] = [];
        for (let i = 0; i < transPathArr.length; i++) {
            if (transPathArr[i] === '..') {
                if (result.length > 0) {
                    result.pop();
                }
            } else if (transPathArr[i] !== '.') {
                result.push(transPathArr[i]);
            }
        }
        return result.length === 0 ? undefined : result.join('.');
    }
    // relative path
    for (let i = 0; i < transPathArr.length; i++) {
        if (transPathArr[i] === '..') {
            // goto parent path
            if (sourcePathArr.length === 0) {
                break;
            }
            sourcePathArr.pop();
        } else if (transPathArr[i] !== '.') {
            // goto child path
            sourcePathArr.push(transPathArr[i]);
        }
    }
    return sourcePathArr.length === 0 ? undefined : sourcePathArr.join('.');
}
